package tr.richfacesext.components.chart;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.charts4j.Color;
import com.googlecode.charts4j.GChart;
import com.googlecode.charts4j.TitledChart;

/**
 * 
 * @author mert
 *
 */
public class ChartRenderer extends Renderer {

	private Logger log = LoggerFactory.getLogger(ChartRenderer.class);

	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
		ResponseWriter writer = context.getResponseWriter();
		Chart chart = (Chart) component;

		addHeaderIfAvailable(context, writer, chart);
		encodeWidget(context, writer, chart);
	}

	private void addHeaderIfAvailable(FacesContext context, ResponseWriter writer, Chart chart) {
		Object header = chart.getAttributes().get("header");
		if (header instanceof String) {
			String headerStr = (String) header;
			
			if (chart.getChart() instanceof TitledChart) {
				TitledChart titledChart = (TitledChart) chart.getChart();
				titledChart.setTitle(headerStr, Color.BLACK, 14);
				chart.setValue(chart.getValue());		
			}
		}
	}

	private void encodeWidget(FacesContext context, ResponseWriter writer, Chart chart) throws IOException {
		chart.getChart().setSize(chart.getWidth(), chart.getHeight());
		
		String onclick = "";
		if (StringUtils.isNotEmpty(chart.getOnclick())) 
			onclick = " onclick='" + chart.getOnclick() + ";'";
		String img = "<img src=\"" + ChartHelper.getChartURL((GChart) chart.getChart()) + "\"" + onclick  +"></img>";
		writer.write(img);
	}
}